/**
 * 完整API测试脚本
 * 用于验证推普活动H5项目的所有API接口
 */

const axios = require('axios');

// 配置
const BASE_URL = 'http://localhost:3001';
let authToken = '';

// 创建axios实例
const api = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    console.error(`❌ 请求失败: ${error.config?.method?.toUpperCase()} ${error.config?.url}`);
    console.error(`   状态码: ${error.response?.status || 'N/A'}`);
    console.error(`   错误信息: ${error.response?.data?.message || error.message}`);
    return Promise.reject(error);
  }
);

// 主测试函数
async function runAllTests() {
  console.log('🚀 开始完整API接口测试...\n');

  const testResults = {
    total: 0,
    passed: 0,
    failed: 0,
    details: []
  };

  try {
    // 1. 系统接口测试
    await testSystemAPIs(testResults);
    
    // 2. 首页接口测试
    await testHomeAPIs(testResults);
    
    // 3. 每日朗读接口测试
    await testDailyAPIs(testResults);
    
    // 4. 游戏接口测试
    await testGameAPIs(testResults);
    
    // 5. 语音检测接口测试
    await testDetectionAPIs(testResults);
    
    // 6. 学习接口测试
    await testStudyAPIs(testResults);
    
    // 生成测试报告
    generateTestReport(testResults);
    
  } catch (error) {
    console.error('\n❌ 测试过程中发生严重错误:', error.message);
  }
}

// 系统接口测试
async function testSystemAPIs(results) {
  console.log('⚙️ 测试系统接口...');
  
  const tests = [
    { path: '/health', name: '健康检查' },
    { path: '/system/info', name: '系统信息' }
  ];
  
  for (const test of tests) {
    await runSingleTest(test.path, test.name, results);
  }
  console.log('');
}

// 首页接口测试
async function testHomeAPIs(results) {
  console.log('🏠 测试首页接口...');
  
  const tests = [
    { path: '/home/banners', name: '轮播图' },
    { path: '/home/functions', name: '功能模块' },
    { path: '/home/activities', name: '活动列表' },
    { path: '/home/statistics', name: '统计数据' },
    { path: '/home/featured', name: '精选推荐' },
    { path: '/home/recommendations?page=1&limit=5', name: '推荐内容' }
  ];
  
  for (const test of tests) {
    await runSingleTest(test.path, test.name, results);
  }
  console.log('');
}

// 每日朗读接口测试
async function testDailyAPIs(results) {
  console.log('📖 测试每日朗读接口...');
  
  const tests = [
    { path: '/daily/sentence', name: '每日一句' },
    { path: '/daily/sentences?page=1&limit=5', name: '历史句子' },
    { path: '/daily/leaderboard', name: '朗读排行榜' }
  ];
  
  for (const test of tests) {
    await runSingleTest(test.path, test.name, results);
  }
  console.log('');
}

// 游戏接口测试
async function testGameAPIs(results) {
  console.log('🎮 测试游戏接口...');
  
  const tests = [
    { path: '/game/contents?count=5', name: '游戏内容' },
    { path: '/game/categories', name: '游戏分类' },
    { path: '/game/daily-challenge', name: '今日挑战' },
    { path: '/game/leaderboard', name: '游戏排行榜' }
  ];
  
  for (const test of tests) {
    await runSingleTest(test.path, test.name, results);
  }
  console.log('');
}

// 语音检测接口测试
async function testDetectionAPIs(results) {
  console.log('🎤 测试语音检测接口...');
  
  const tests = [
    { path: '/detection/texts?page=1&limit=5', name: '检测文本' },
    { path: '/detection/texts/random', name: '随机文本' },
    { path: '/detection/leaderboard', name: '检测排行榜' }
  ];
  
  for (const test of tests) {
    await runSingleTest(test.path, test.name, results);
  }
  console.log('');
}

// 学习接口测试
async function testStudyAPIs(results) {
  console.log('📚 测试学习接口...');
  
  const tests = [
    { path: '/study/categories', name: '课程分类' },
    { path: '/study/courses/recommended?page=1&limit=5', name: '推荐课程' },
    { path: '/study/courses/search?keyword=普通话&page=1&limit=5', name: '课程搜索' }
  ];
  
  for (const test of tests) {
    await runSingleTest(test.path, test.name, results);
  }
  console.log('');
}

// 执行单个测试
async function runSingleTest(path, name, results) {
  results.total++;
  
  try {
    const response = await api.get(path);
    
    if (response.status === 200 && response.data.code === 200) {
      console.log(`✅ ${name}接口正常`);
      results.passed++;
      results.details.push({
        name,
        path,
        status: 'PASS',
        message: '接口响应正常'
      });
      
      // 显示数据信息
      if (response.data.data) {
        if (Array.isArray(response.data.data)) {
          console.log(`   返回${response.data.data.length}条数据`);
        } else if (response.data.data.list && Array.isArray(response.data.data.list)) {
          console.log(`   返回${response.data.data.list.length}条数据`);
        } else if (typeof response.data.data === 'object') {
          console.log(`   返回对象数据`);
        }
      }
    } else {
      throw new Error(`响应状态异常: ${response.status}, code: ${response.data.code}`);
    }
    
  } catch (error) {
    console.log(`❌ ${name}接口异常`);
    console.log(`   错误: ${error.message}`);
    results.failed++;
    results.details.push({
      name,
      path,
      status: 'FAIL',
      message: error.message
    });
  }
}

// 生成测试报告
function generateTestReport(results) {
  console.log('\n📊 测试报告');
  console.log('==========================================');
  console.log(`测试时间: ${new Date().toLocaleString()}`);
  console.log(`服务器地址: ${BASE_URL}`);
  console.log(`总测试数: ${results.total}`);
  console.log(`通过数: ${results.passed}`);
  console.log(`失败数: ${results.failed}`);
  console.log(`成功率: ${((results.passed / results.total) * 100).toFixed(1)}%`);
  console.log('');
  
  if (results.failed > 0) {
    console.log('❌ 失败的接口:');
    results.details
      .filter(detail => detail.status === 'FAIL')
      .forEach(detail => {
        console.log(`   - ${detail.name} (${detail.path}): ${detail.message}`);
      });
    console.log('');
  }
  
  console.log('📝 测试说明:');
  console.log('- 本次测试仅包含无需认证的公开接口');
  console.log('- 需要认证的接口需要有效的用户名密码');
  console.log('- 文件上传接口需要实际文件进行测试');
  console.log('');
  console.log('🔗 相关文档:');
  console.log('- 完整API文档: API_DOCUMENTATION_COMPLETE.md');
  console.log('- 快速参考: API_QUICK_REFERENCE.md');
  console.log('==========================================');
}

// 认证接口测试（可选）
async function testAuthAPIs() {
  console.log('🔐 测试认证接口（需要有效凭据）...');
  
  // 这里可以添加认证接口的测试
  // 需要提供有效的用户名和密码
  console.log('⚠️ 认证接口测试需要有效的用户凭据，已跳过');
  console.log('');
}

// 主函数
async function main() {
  console.clear();
  console.log('🎯 推普活动H5项目 - 完整API接口测试');
  console.log('==========================================\n');
  
  await runAllTests();
}

// 运行测试
if (require.main === module) {
  main().catch(console.error);
}

module.exports = {
  runAllTests,
  testSystemAPIs,
  testHomeAPIs,
  testDailyAPIs,
  testGameAPIs,
  testDetectionAPIs,
  testStudyAPIs
};
